package com.xhwl.data.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.*;
import com.xhwl.common.enums.AppTypeEnum;
import com.xhwl.common.enums.BusinessRangeTypeEnum;
import com.xhwl.common.enums.MenuTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.IndustryEnum;
import com.xhwl.common.enums.config.PermissionTypeEnum;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.ParameterConfig;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.pojo.criteria.ParamConfigCriteria;
import com.xhwl.common.query.cent.sdata.AppQuery;
import com.xhwl.common.query.cent.sdata.PermissionQuery;
import com.xhwl.data.dao.*;
import com.xhwl.data.service.*;
import com.xhwl.data.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;


/**
 * @description:
 * @author:
 * @create: 2020-11-25
 **/
@Service
public class PermissionServiceImpl extends ServiceImpl<IPermissionDao, Permission> implements IPermissionService {

    private static final Logger log = LoggerFactory.getLogger(PermissionServiceImpl.class);
    @Autowired
    IRoleService roleService;
    @Autowired
    private IEnterpriseProjectDao enterpriseProjectDao;
    @Autowired
    IAccountService accountService;
    @Autowired
    IProjectService projectService;
    @Autowired
    IEnterprisePermissionService enterprisePermissionService;
    @Autowired
    IProjectPermissionService projectPermissionService;
    @Autowired
    IRolePermissionService rolePermissionService;
    @Autowired
    private IEnterprisePermissionDao enterprisePermissionDao;
    @Autowired
    IAppService appService;
    @Autowired
    IAccountProjectService accountProjectService;
    @Autowired
    IAccountRoleService accountRoleService;
    @Autowired
    IPermissionDao permissionDao;
    @Autowired
    IAccountOrganizationDao accountOrganizationDao;
    @Autowired
    IAppDao appDao;
    @Autowired
    IParameterConfigService parameterConfigService;
    @Autowired
    private IAdminAccountRoleService adminAccountRoleService;
    @Autowired
    private IPermissionGroupService permissionGroupService;
    @Autowired
    private IPermissionAuthService permissionAuthService;
    @Autowired
    private IEnterpriseService enterpriseService;
    @Autowired
    private ISceneDao sceneDao;
    @Autowired
    private ISceneAppDao sceneAppDao;
    @Autowired
    private ISceneProjectDao sceneProjectDao;
    @Autowired
    private ISceneEnterpriseDao sceneEnterpriseDao;

    private static final List<String> EXCLUDE_ENTERPRISE_PERMISSION = Arrays.asList("enterpriseAdd", "enterpriseModify");
    private static final String SYSTEM_SETTING_PERMISSION = "systemSetting";
    /**
     * 创建权限
     *
     * @param appPermissionDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson createPermission(AppPermissionDTO appPermissionDTO) {
        if (StringUtils.isEmpty(appPermissionDTO.getAppId())) {
            log.info("创建权限，没有传入appId，appPermissionDTO={}", appPermissionDTO.toString());
            return ResultJson.fail("缺少appId");
        }
        if (StringUtils.isEmpty(appPermissionDTO.getCode())) {
            log.info("创建权限，没有传入code，appPermissionDTO={}", appPermissionDTO.toString());
            return ResultJson.fail("缺少code");
        }
        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_id", appPermissionDTO.getAppId()).or().eq("id", appPermissionDTO.getAppId());
        App app = appDao.selectOne(appQueryWrapper);
        if (null == app) {
            log.info("appId={} 查找相关数据 异常，需要确认数据库app表数据", appPermissionDTO.getAppId());
            throw new DataException("app数据异常");
        }
        if (null == appPermissionDTO.getIndustryId()) {
            if (null == app.getIndustryId()) {
                throw new DataException("当前app数据异常，缺少业态id");
            }
            appPermissionDTO.setIndustryId(app.getIndustryId());
        }

        if (null == appPermissionDTO.getLevel()) {
            throw new DataException("菜单层级参数不能为空，请核实");
        }

        if (null == appPermissionDTO.getMenuType()) {
            throw new DataException("菜单类型不能为空，请核实");
        }

        //父级菜单，parentId兼容
        if (1 == appPermissionDTO.getLevel()) {
            Integer parentId = appPermissionDTO.getParentId();
            if (null == parentId) {
                appPermissionDTO.setParentId(0);
            }
        } else {
            checkParent(appPermissionDTO);
        }
        log.info("创建权限,权限数据={}", appPermissionDTO.toString());
        Permission permission = new Permission();
        BeanUtils.copyProperties(appPermissionDTO, permission);
        permission.setIsDeleted(false);
        permission.setAppId(app.getId());
        //权限码 验重
        Boolean permissionCodeExistResult = permissionCodeExistChecking(permission.getSceneCode(), permission.getAppId(), permission.getCode());
        if (permissionCodeExistResult) {
            throw new BusinessException("权限码已存在,创建失败");
        }
        //首页验重，同场景下
        if(permission.getHomeFlag() != null && 1==permission.getHomeFlag()) {
            QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scene_code", permission.getSceneCode());
            queryWrapper.eq("app_id", permission.getAppId());
            queryWrapper.eq("home_flag", permission.getHomeFlag());
            List<Permission> permissions = permissionDao.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(permissions)) {
                log.warn("该场景下已有首页,更新失败，传入的appPermissionDTO={}", appPermissionDTO.toString());
                throw new BusinessException("该场景下已有首页,更新失败");
            }
        }
        save(permission);
        return ResultJson.success(permission.getId());
    }

    /**
     * 修改权限 、 APP关联
     *
     * @param appPermissionDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson updatePermission(AppPermissionDTO appPermissionDTO) {

        log.info("更新获取的参数是={}", appPermissionDTO.toString());
        log.info("更新获取的默认展示设置参数是={}", appPermissionDTO.getDefaultShow());

        QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
        appQueryWrapper.eq("app_id", appPermissionDTO.getAppId()).or().eq("id", appPermissionDTO.getAppId());
        App app = appDao.selectOne(appQueryWrapper);
        if (Objects.isNull(app)) {
            log.warn("传入的appId在数据库内查找不到对应数据，appPermissionDTO={}", appPermissionDTO.toString());
            return ResultJson.fail("appId参数异常");
        }
        if (Objects.isNull(appPermissionDTO.getIndustryId())) {
            appPermissionDTO.setIndustryId(app.getIndustryId());
        }
        Permission permission = new Permission();
        BeanUtils.copyProperties(appPermissionDTO, permission);
        permission.setAppId(app.getId());
        Integer permissionId = permission.getId();
        if (Objects.isNull(permissionId)) {
            throw new BusinessException("缺少权限数据");
        }
        Permission permissionExist = permissionDao.selectById(permissionId);
        if (Objects.isNull(permissionExist)) {
            throw new BusinessException("权限数据不存在");
        }
        checkParent(appPermissionDTO);
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("scene_code", permission.getSceneCode());
        queryWrapper.eq("app_id", permission.getAppId());
        queryWrapper.eq("code", permission.getCode());
        Permission permissionDb = permissionDao.selectOne(queryWrapper);
        if (Objects.nonNull(permissionDb)) {
            Integer idDb = permissionDb.getId();
            if (!permissionId.equals(idDb)) {
                log.warn("权限码已存在,更新失败，传入的appPermissionDTO={}", appPermissionDTO.toString());
                throw new BusinessException("该业态下，当前appId的当前权限码已存在,更新失败");
            }
        }
        //首页验重，同场景下
        if(permission.getHomeFlag() != null && 1==permission.getHomeFlag()) {
            QueryWrapper<Permission> homeWrapper = new QueryWrapper<>();
            homeWrapper.eq("scene_code", permission.getSceneCode());
            homeWrapper.eq("app_id", permission.getAppId());
            homeWrapper.eq("home_flag", permission.getHomeFlag());
            List<Permission> permissions = permissionDao.selectList(homeWrapper);
            if (!CollectionUtils.isEmpty(permissions)) {
                for(Permission vo : permissions){
                    if(!permissionId.equals(vo.getId())){
                        log.warn("该场景下已有首页,更新失败，传入的appPermissionDTO={}", appPermissionDTO.toString());
                        throw new BusinessException("该场景下已有首页,更新失败");
                    }
                }
            }
        }
        permission.setUpdatedAt(new Date());
        UpdateWrapper<Permission> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", permissionId);
        boolean updateResult = update(permission, updateWrapper);
        if (!updateResult) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException("更新权限数据失败");
        }
        log.warn("权限更新成功");
        return ResultJson.success();
    }

    /**
     * 检查数据准确性，校验上级
     * @param appPermissionDTO
     */
    private void checkParent(AppPermissionDTO appPermissionDTO) {
        if(null != appPermissionDTO.getParentId() && appPermissionDTO.getParentId() > 0){
            Permission permission = permissionDao.selectById(appPermissionDTO.getParentId());
            if(null == permission){
                throw new DataException("上级id不存在");
            }
            // 查询上级的app
            App app = appService.getAppById(permission.getAppId());
            if (!appPermissionDTO.getAppId().equals(app.getAppId())) {
                throw new DataException("父级菜单/按钮 所属的app与当前菜单/按钮不一致");
            }
        }

    }

    /**
     * 动态获取 权限码list
     *
     * @param page
     * @param permissionQuery
     * @return
     */
    @Override
    public Page<Permission> getPermissionPageList(Page page, PermissionQuery permissionQuery) {
        //通过账号关联查询 permission列表信息
        if (null != permissionQuery && null != permissionQuery.getAccountId()) {
            PermissionQuery permissionRoleQuery = new PermissionQuery();
            BeanUtils.copyProperties(permissionRoleQuery, permissionQuery);
            Integer operateAccountId = permissionQuery.getAccountId();
            Account account = new Account();
            account.setId(operateAccountId);
            RoleTypeEnum roleTypeEnum = roleService.getAccountRoleType(operateAccountId).getRoleTypeEnum();
            //超管特殊处理 -业态下所有的角色权限 permissionCode都能拥有
            if (roleTypeEnum.equals(RoleTypeEnum.SUPPER_MANAGER)) {
                List<Role> roleList = roleService.getRoleList(account, null);
                List<Integer> roleIdList = roleList.stream().map(Role::getId).collect(Collectors.toList());
                List<Integer> rolePermissionList = rolePermissionService.getPermissionIdByRoleId(roleIdList);
                if (!CollectionUtils.isEmpty(permissionQuery.getIdList())) {
                    List<Integer> overlapId = rolePermissionList.stream().filter(permissionQuery.getIdList()::contains).collect(Collectors.toList());
                    permissionRoleQuery.setIdList(overlapId);
                } else {
                    permissionRoleQuery.setIdList(rolePermissionList);
                }
                permissionRoleQuery.setOrderColumn("sort_num");
                permissionRoleQuery.setOrderAsc(false);
                return permissionDao.selectPage(page, handleParams(permissionRoleQuery));
            }
            Page<Permission> permissionList = new Page<>();
            List<Integer> roleIdList = accountRoleService.findRoleIdByAccountId(account.getId());
            if (CollectionUtils.isEmpty(roleIdList)) {
                log.warn("该人员 {} {} 暂未关联角色信息", account.getLoginName(), account.getName());
                return permissionList;
            }
            List<Integer> rolePermissionList = rolePermissionService.getPermissionIdByRoleId(roleIdList);
            if (CollectionUtils.isEmpty(rolePermissionList)) {
                log.warn("该帐号 {} {} 没有权限信息", account.getLoginName(), account.getName());
                return permissionList;
            }
            if (!CollectionUtils.isEmpty(permissionQuery.getIdList())) {
                List<Integer> overlapId = rolePermissionList.stream().filter(permissionQuery.getIdList()::contains).collect(Collectors.toList());
                permissionRoleQuery.setIdList(overlapId);
            } else {
                permissionRoleQuery.setIdList(rolePermissionList);
            }
            permissionRoleQuery.setOrderColumn("sort_num");
            permissionRoleQuery.setOrderAsc(false);
            return permissionDao.selectPage(page, handleParams(permissionRoleQuery));
        }
        //单表查询 permission列表信息
        return permissionDao.selectPage(page, handleParams(permissionQuery));
    }

    @Override
    public List<Permission> getPermissionList(PermissionQuery permissionQuery) {
        //通过账号关联查询 permission列表信息
        if (null != permissionQuery && null != permissionQuery.getAccountId()) {
            PermissionQuery permissionRoleQuery = new PermissionQuery();
            BeanUtils.copyProperties(permissionQuery, permissionRoleQuery);
            Integer operateAccountId = permissionQuery.getAccountId();
            log.info("正在查询与账号相关的权限信息，operateAccountId={}", operateAccountId);
            Account account = new Account();
            account.setId(operateAccountId);
            RoleTypeDTO accountRoleInfos = roleService.getAccountRoleType(operateAccountId);
            RoleTypeEnum roleTypeEnum = accountRoleInfos.getRoleTypeEnum();
            //超管特殊处理 -业态下所有的角色权限 permissionCode都能拥有
            if (roleTypeEnum.equals(RoleTypeEnum.SUPPER_MANAGER)) {
                log.info("当前查找权限的角色为超管，operateAccountId={}", operateAccountId);
                //把当前超管能管理的所有的业态权限都获取出来
                List<Short> industryIdList = accountRoleInfos.getIndustryIdList();
                QueryWrapper<Permission> permissionsWrapper = new QueryWrapper<>();
                permissionsWrapper.in("industry_id", industryIdList);
                List<Permission> permissionsList = permissionDao.selectList(permissionsWrapper);
                List<Integer> permissionDbIds = permissionsList.stream().map(e -> e.getId()).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(permissionQuery.getIdList())) {
                    List<Integer> overlapId = permissionDbIds.stream().filter(permissionQuery.getIdList()::contains).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(overlapId)) {
                        return Collections.emptyList();
                    }
                    permissionRoleQuery.setIdList(overlapId);
                } else {
                    permissionRoleQuery.setIdList(permissionDbIds);
                }
                permissionRoleQuery.setOrderColumn("sort_num");
                permissionRoleQuery.setOrderAsc(false);
                List<Permission> permissions = permissionDao.selectList(handleParams(permissionRoleQuery));
                return permissions;
            }
            List<Permission> permissionList = new ArrayList<>();
            List<Integer> roleIdList = accountRoleService.findRoleIdByAccountId(account.getId());
            if (CollectionUtils.isEmpty(roleIdList)) {
                log.warn("该人员 {} {} 暂未关联角色信息", account.getLoginName(), account.getName());
                return permissionList;
            }
            List<Integer> rolePermissionList = rolePermissionService.getPermissionIdByRoleId(roleIdList);
            if (CollectionUtils.isEmpty(rolePermissionList)) {
                log.warn("该帐号 {} {} 没有权限信息", account.getLoginName(), account.getName());
                return permissionList;
            }
            if (!CollectionUtils.isEmpty(permissionQuery.getIdList())) {
                List<Integer> overlapId = rolePermissionList.stream().filter(permissionQuery.getIdList()::contains).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(overlapId)) {
                    return Collections.emptyList();
                }
                permissionRoleQuery.setIdList(overlapId);
            } else {
                permissionRoleQuery.setIdList(rolePermissionList);
            }
            permissionRoleQuery.setOrderColumn("sort_num");
            permissionRoleQuery.setOrderAsc(false);
            List<Permission> permissions = permissionDao.selectList(handleParams(permissionRoleQuery));
            return permissions;
        }
        //单表查询 permission列表信息
        List<Permission> permissions = permissionDao.selectList(handleParams(permissionQuery));
        return permissions;
    }

    /**
     * 获取权限树
     *
     * @param permissionTreeDTO
     * @param account
     * @return
     */
    @Override
    public List<AppPermissionMenuDTO> getPermissionTree(PermissionTreeDTO permissionTreeDTO, Account account) {
        List<Permission> permissions = null;
        RoleTypeEnum accountManagerType = roleService.getAccountRoleType(account.getId()).getRoleTypeEnum();
        if (RoleTypeEnum.SUPPER_MANAGER.equals(accountManagerType)) {
            if (Objects.nonNull(permissionTreeDTO.getProjectId())) {
                permissions = getListByProjectId(permissionTreeDTO.getExcludeIds(), permissionTreeDTO.getProjectId());
            } else if (Objects.nonNull(permissionTreeDTO.getEnterpriseId())) {
                permissions = getListByEnterpriseId(permissionTreeDTO.getExcludeIds(), permissionTreeDTO.getEnterpriseId());
            } else {
                if (!CollectionUtils.isEmpty(permissionTreeDTO.getExcludeIds())) {
                    PermissionQuery permissionQuery = new PermissionQuery();
                    permissionQuery.setExcludeIdList(permissionTreeDTO.getExcludeIds());
                    permissions = getPermissionList(permissionQuery);
                } else {
                    permissions = getPermissionList(null);
                }
            }
        } else if (Objects.nonNull(permissionTreeDTO.getProjectId())) {
            permissions = getListByProjectId(permissionTreeDTO.getExcludeIds(), permissionTreeDTO.getProjectId());
        } else if (Objects.nonNull(permissionTreeDTO.getEnterpriseId())) {
            permissions = getEnterprisePermissions(permissionTreeDTO);
        } else {
            return Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(permissions)) {
            return Collections.emptyList();
        }
        //除去按钮
        List<Permission> result = permissions.stream().filter(p -> p.getMenuType() != 0).collect(Collectors.toList());
        List<PermissionDTO> permissionTotalList;
        //移除管理类型菜单
        if (!permissionTreeDTO.getNeedAdmin()) {
            List<Permission> removeAdminPermissions = result.stream().filter(permission -> PermissionTypeEnum.BUSINESS.getCode().equals(permission.getType())).collect(toCollection(LinkedList::new));
            if (CollectionUtils.isEmpty(removeAdminPermissions)) {
                return Collections.emptyList();
            }
            //生成不带有管理权限的权限树
            //根据app将权限树分组
            permissionTotalList = generateTree(removeAdminPermissions);
            Permission permission = removeAdminPermissions.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList()).get(0);
            for (int i = 0; i < permission.getLevel(); i ++) {
                permissionCut(permissionTotalList);
            }
            return getPermissionTreeGroupByApp(permissionTotalList);
        }
        //生成权限树
        //根据app将权限树分组
        permissionTotalList = generateTree(result);
        Permission permission = result.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList()).get(0);
        for (int i = 0; i < permission.getLevel(); i ++) {
            permissionCut(permissionTotalList);
        }
        return getPermissionTreeGroupByApp(permissionTotalList);
    }

    /**
     * 将权限树根据appId分组
     *
     * @param permissionTotalList
     * @return
     */
    @Override
    public List<AppPermissionMenuDTO> getPermissionTreeGroupByApp(List<PermissionDTO> permissionTotalList) {
        List<AppPermissionMenuDTO> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(permissionTotalList)) {
            log.warn("缺少权限信息");
            return resultList;
        }
        List<Integer> appKeyIdList = permissionTotalList.stream().map(PermissionDTO::getAppId).collect(Collectors.toList());
        appKeyIdList=appKeyIdList.stream().distinct().collect(Collectors.toList());
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", appKeyIdList);
        List<App> apps = appDao.selectList(queryWrapper);
        Map<Integer, App> appKeyIdMap = apps.stream().collect(Collectors.toMap(App::getId, Function.identity()));
        Map<String, App> appStrIdMap = apps.stream().collect(Collectors.toMap(App::getAppId, Function.identity()));
        List<String> appIdList = apps.stream().map(App::getAppId).collect(Collectors.toList());
        Map<String, List<PermissionDTO>> resultMap = new HashMap<>(appIdList.size());
        for (String appId : appIdList) {
            List<PermissionDTO> permissionDTOList = new ArrayList<>();
            resultMap.put(appId, permissionDTOList);
        }
        for (PermissionDTO permissionDTO : permissionTotalList) {
            Integer appKeyId = permissionDTO.getAppId();
            App app = appKeyIdMap.get(appKeyId);
            PermissionDTO permission = new PermissionDTO();
            BeanUtils.copyProperties(permissionDTO, permission);
            List<PermissionDTO> permissionList = resultMap.get(app.getAppId());
            permissionList.add(permission);
        }
        for (Map.Entry<String, List<PermissionDTO>> entry : resultMap.entrySet()) {
            String appId = entry.getKey();
            List<PermissionDTO> value = entry.getValue();
            App app = appStrIdMap.get(appId);
            //区分标识
            Random random = new Random();
            int range = random.nextInt(10000);
            app.setRundStr(app.getAppId()+range);
            AppPermissionMenuDTO appPermissionMenuDTO = new AppPermissionMenuDTO();
            appPermissionMenuDTO.setApp(app);
            appPermissionMenuDTO.setPermissions(value);
            resultList.add(appPermissionMenuDTO);
        }
        return resultList;
    }

    /**
     * 根据账号查找权限菜单
     *
     * @param account
     * @return
     */
    @Override
    public List<PermissionDTO> getPermissionTreeByAccount(Account account, Integer projectId, String appId) {
        App app = appService.getByAppId(appId);
        if (null == app) {
            log.info("当前数据库无此appId相关数据，请核实");
            throw new DataException("app参数有误");
        }
        List<Permission> permissions = null;
        RoleTypeEnum accountManagerType = roleService.getAccountRoleType(account.getId()).getRoleTypeEnum();

        if (RoleTypeEnum.SUPPER_MANAGER.equals(accountManagerType)) {
            permissions = rolePermissionService.getSuperManagerPermission(account);
        } else if (RoleTypeEnum.ENT_MANAGER.equals(accountManagerType)) {
            // 企业管理员获取企业下的所有权限
            List<Role> roleListByAccountId = roleService.getRoleListByAccountId(account.getId());
            List<Integer> entId = roleListByAccountId.stream().filter(i -> null != i.getEnterpriseId()).map(j -> j.getEnterpriseId()).distinct().collect(Collectors.toList());
            QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
            enterprisePermissionQueryWrapper.in("enterprise_id", entId.stream().distinct().collect(Collectors.toList()));
            List<EnterprisePermission> list = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
            PermissionQuery permissionQuery = new PermissionQuery();
            permissionQuery.setIdList(list.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList()));
            permissionQuery.setOrderColumn("sort_num");
            permissionQuery.setOrderAsc(false);
            //账号权限信息
            permissions = getPermissionList(permissionQuery);
        } else {
            permissions = rolePermissionService.getCommonAccountPermission(projectId, account, app);
        }
        if (CollectionUtils.isEmpty(permissions)) {
            //如果是app类型，需要加入默认的菜单去重
            if (AppTypeEnum.APP.getType() == app.getAppType()) {
                //将属于这个app的所有菜单获取出来
                List<Permission> allAppPermissions = getDefaultPermissions(appId, false);
                List<Permission> resultList = new ArrayList<>();
                if (null != projectId) {
                    List<Integer> projectPermissionList = projectPermissionService.list(Arrays.asList(projectId));
                    for (Permission permission : allAppPermissions) {
                        Integer permissionId = permission.getId();
                        if (projectPermissionList.contains(permissionId)) {
                            resultList.add(permission);
                        }
                    }
                } else {
                    List<Permission> defaultPermissions = getDefaultPermissions(appId, false);
                    resultList.addAll(defaultPermissions);
                }
                Set<Permission> permissionSet = new HashSet<>(resultList);
                return generateTree(new ArrayList<>(permissionSet));
            }
            return Collections.emptyList();
        }
        //项目id不为空，则需要将账号的权限 与当前选择项目的权限 做交集处理 只交集项目范围权限
        if (Objects.nonNull(projectId)) {

            // 企业关联的项目级权限
            List<Integer> collect = permissions.stream().filter(i -> i.getType() == PermissionTypeEnum.PROJECT.type).map(i -> i.getId()).collect(Collectors.toList());

            // 项目关联的项目级权限
            QueryWrapper<ProjectPermission> projectPermissionQueryWrapper = new QueryWrapper<>();
            projectPermissionQueryWrapper.eq("project_id",  projectId);
            List<ProjectPermission> list = projectPermissionService.list(projectPermissionQueryWrapper);

            if(list.isEmpty()){
                // 去除项目级权限
                permissions = permissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
            }else{
                // 移除项目里没有的
                List<Integer> collect1 = list.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
                List<Integer> collect2 = collect.stream().filter(i -> !collect1.contains(i)).collect(Collectors.toList());
                permissions = permissions.stream().filter(i -> !collect2.contains(i)).collect(Collectors.toList());
            }
        }
        log.info("账号{} {} 权限菜单查询完成，开始生成树", account.getLoginName(), account.getName());
        Integer appKeyId = app.getId();
        List<Permission> resultList = new ArrayList<>();
        for (Permission permission : permissions) {
            Integer appKeyIdDb = permission.getAppId();
            if (appKeyId.equals(appKeyIdDb)) {
                resultList.add(permission);
            }
        }
        if (RoleTypeEnum.SUPPER_MANAGER.equals(accountManagerType)) {
            //填充企业级屏蔽按钮
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.in("code", EXCLUDE_ENTERPRISE_PERMISSION);
            List<Permission> extraPermissions = permissionDao.selectList(permissionQueryWrapper);
            resultList.addAll(extraPermissions);
        }

        //如果是app类型，需要加入默认的菜单去重
        if (AppTypeEnum.APP.getType() == app.getAppType()) {
            //将属于这个app的所有菜单获取出来
            List<Permission> defaultPermissions = getDefaultPermissions(appId, false);
            resultList.addAll(defaultPermissions);
            Set<Permission> permissionSet = new HashSet<>(resultList);
            return generateTree(new ArrayList<>(permissionSet));
        }

        resultList = resultList.stream().distinct().collect(Collectors.toList());
        return generateTree(resultList);
    }

    @Override
    public List<PermissionDTO> getPermissionTreeByAccount(Account account, PermissionQuery permissionQuery1, String appId) {
        App app = appService.getByAppId(appId);
        if (null == app) {
            log.info("当前数据库无此appId相关数据，请核实");
            throw new DataException("app参数有误");
        }
        List<Permission> permissions = new ArrayList<>();
        RoleTypeEnum accountManagerType = roleService.getAccountRoleType(account.getId()).getRoleTypeEnum();
        Integer projectId = permissionQuery1.getProjectId();
        if (RoleTypeEnum.SUPPER_MANAGER.equals(accountManagerType)) {
            permissions = rolePermissionService.getSuperManagerPermission(account);
        } else if (RoleTypeEnum.ENT_MANAGER.equals(accountManagerType)) {
            // 企业管理员获取企业下的所有权限
            List<Integer> entId = new ArrayList<>();
            if(null != permissionQuery1.getEnterpriseId()){
                entId.add(permissionQuery1.getEnterpriseId());
            }else{
                List<Role> roleListByAccountId = roleService.getRoleListByAccountId(account.getId());
                entId = roleListByAccountId.stream().filter(i -> null != i.getEnterpriseId()).map(j -> j.getEnterpriseId()).distinct().collect(Collectors.toList());
            }
            QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
            enterprisePermissionQueryWrapper.in("enterprise_id", entId.stream().distinct().collect(Collectors.toList()));
            List<EnterprisePermission> list = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
            PermissionQuery permissionQuery = new PermissionQuery();
            permissionQuery.setIdList(list.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList()));
            permissionQuery.setOrderColumn("sort_num");
            permissionQuery.setOrderAsc(false);
            //账号权限信息
            List<Permission> permissionList = getPermissionList(permissionQuery);
            permissions.addAll(permissionList);
        }
        // 获取非与企业管理员的权限
        List<Permission> permissions1 = getPermissions(permissionQuery1);
        permissions.addAll(permissions1);
        if (CollectionUtils.isEmpty(permissions)) {
            //如果是app类型，需要加入默认的菜单去重
            if (AppTypeEnum.APP.getType() == app.getAppType()) {
                //将属于这个app的所有菜单获取出来
                List<Permission> allAppPermissions = getDefaultPermissions(appId, false);
                List<Permission> resultList = new ArrayList<>();
                if (null != projectId) {
                    List<Integer> projectPermissionList = projectPermissionService.list(Arrays.asList(projectId));
                    for (Permission permission : allAppPermissions) {
                        Integer permissionId = permission.getId();
                        if (projectPermissionList.contains(permissionId)) {
                            resultList.add(permission);
                        }
                    }
                } else {
                    List<Permission> defaultPermissions = getDefaultPermissions(appId, false);
                    resultList.addAll(defaultPermissions);
                }
                Set<Permission> permissionSet = new HashSet<>(resultList);
                return generateTree(new ArrayList<>(permissionSet));
            }
            return Collections.emptyList();
        }
        //项目id不为空，则需要将账号的权限 与当前选择项目的权限 做交集处理 只交集项目范围权限
        if (Objects.nonNull(projectId)) {

            // 企业关联的项目级权限
            List<Integer> enterprisePermission = permissions.stream().filter(i -> i.getType() == PermissionTypeEnum.PROJECT.type).map(i -> i.getId()).collect(Collectors.toList());

            // 项目关联的项目级权限
            List<ProjectPermission> list = getProjectPermission(projectId, permissionQuery1.getEnterpriseId());
            if(list.isEmpty()){
                // 去除项目级权限
                permissions = permissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
            }else{
                // 移除项目里没有的
                List<Integer> collect1 = list.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
                // 企业权限中的项目范围与项目中的权限没有交集的部分collect2
                List<Integer> collect2 = enterprisePermission.stream().filter(i -> !collect1.contains(i)).collect(Collectors.toList());
                // 在权限中移除这些collect2
                permissions = permissions.stream().filter(i -> !collect2.contains(i.getId())).collect(Collectors.toList());
            }
        }else{
            permissions = permissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
        }
        log.info("账号{} {} 权限菜单查询完成，开始生成树", account.getLoginName(), account.getName());
        Integer appKeyId = app.getId();
        List<Permission> resultList = new ArrayList<>();
        for (Permission permission : permissions) {
            Integer appKeyIdDb = permission.getAppId();
            if (appKeyId.equals(appKeyIdDb)) {
                resultList.add(permission);
            }
        }
        if (RoleTypeEnum.SUPPER_MANAGER.equals(accountManagerType)) {
            //填充企业级屏蔽按钮
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.in("code", EXCLUDE_ENTERPRISE_PERMISSION);
            List<Permission> extraPermissions = permissionDao.selectList(permissionQueryWrapper);
            resultList.addAll(extraPermissions);
        }
        //如果是app类型，需要加入默认的菜单去重
        if (AppTypeEnum.APP.getType() == app.getAppType()) {
            //将属于这个app的所有菜单获取出来
            List<Permission> defaultPermissions = getDefaultPermissions(appId, false);
            resultList.addAll(defaultPermissions);
            Set<Permission> permissionSet = new HashSet<>(resultList);
            return generateTree(new ArrayList<>(permissionSet));
        }
        List<PermissionDTO> permissionDTOS = generateTree(resultList);
        if(CollectionUtils.isEmpty(permissionDTOS)){
            return permissionDTOS;
        }
        Permission permission = resultList.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList()).get(0);
        for (int i = 0; i < permission.getLevel(); i ++){
            permissionCut(permissionDTOS);
        }
        return permissionDTOS;
    }

    /**
     * 获取项目权限
     * @param projectId
     * @param enterpriseId
     * @return
     */
    private List<ProjectPermission> getProjectPermission(Integer projectId, Integer enterpriseId){
        //if(enterpriseService.isOperator(enterpriseId)){
            QueryWrapper<ProjectPermission> projectPermissionQueryWrapper = new QueryWrapper<>();
            projectPermissionQueryWrapper.eq("project_id",  projectId);
            return projectPermissionService.list(projectPermissionQueryWrapper);
        /*}else{
            // 如果是非运营商
            QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
            enterprisePermissionQueryWrapper.eq("enterprise_id", enterpriseId);
            enterprisePermissionQueryWrapper.eq("project_id", projectId);
            List<EnterprisePermission> list = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
            if(!list.isEmpty()){
                List<ProjectPermission> projectPermissions = new ArrayList<>(list.size());
                for (EnterprisePermission enterprisePermission : list) {
                    ProjectPermission projectPermission = new ProjectPermission();
                    projectPermission.setPermissionId(enterprisePermission.getPermissionId());
                    projectPermission.setProjectId(enterprisePermission.getProjectId());
                    projectPermissions.add(projectPermission);
                }
                return projectPermissions;
            }else{
                return Collections.emptyList();
            }
        }*/
    }


    @Override
    public List<PermissionDTO> getChild(Integer id, List<Permission> allPermission,List<Permission> resultPermission) {

        //子菜单
        List<PermissionDTO> childList = new ArrayList<PermissionDTO>();
        for (Permission nav : allPermission) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (null==nav.getParentId()){
                throw new DataException("菜单数据异常，父级id不应该为空，请核实修复");
            }
            if(nav.getParentId().equals(id)){
                PermissionDTO permissionDTO=new PermissionDTO();
                BeanUtils.copyProperties(nav,permissionDTO);
                childList.add(permissionDTO);
                //平级填充
                resultPermission.add(nav);
            }
        }
        //递归
        for (PermissionDTO nav : childList) {
            nav.setChildren(getChild(nav.getId(), allPermission,resultPermission));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if(childList.size() == 0){
            return new ArrayList<PermissionDTO>();
        }
        return childList;

    }

    /**
     * 获取默认菜单
     *
     * @param appId
     * @return
     */
    @Override
    public List<PermissionDTO> getDefaultPermissionTree(String appId, Boolean needAll) {
        App app = appService.getByAppId(appId);
        if (Objects.isNull(app)) {
            log.info("当前数据库无此appId={}相关数据，请核实",appId);
          throw new DataException("app数据异常");
        }

        List<Permission> permissions = getDefaultPermissions(appId, needAll);
        List<Permission> permissionList = new ArrayList<>();
        Integer appKeyId = app.getId();
        for (Permission permission : permissions) {
            Integer appKeyIdDb = permission.getAppId();
            if (appKeyId.equals(appKeyIdDb)) {
                permissionList.add(permission);
            }
        }
        return generateTree(permissionList);
    }

    /**
     * 获取当前app 的默认加载权限
     *
     * @param appId
     * @return
     */
    @Override
    public List<Permission> getDefaultPermissions(String appId, Boolean needAll) {
        App app = appService.getByAppId(appId);
        if (Objects.isNull(app)) {
            log.info("当前数据库无此appId={}相关数据，请核实",appId);
            throw new DataException("app数据异常");
        }
        Integer appKeyId = app.getId();
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        if (!needAll) {
            permissionQueryWrapper.eq("default_show", true);
        }
        permissionQueryWrapper.eq("app_id", appKeyId);
        permissionQueryWrapper.eq("is_deleted", false);
        return permissionDao.selectList(permissionQueryWrapper);
    }

//    @Override
//    public void batchAddProjectPermissions(List<Integer> projectIdList, List<Integer> permissionIdList) {
//        permissionCore.batchAddProjectPermissions(projectIdList, permissionIdList);
//    }

//    @Override
//    public void batchDeleteProjectPermissions(List<Integer> projectIdList, List<Integer> permissionIdList) {
//        permissionCore.batchDeleteProjectPermissions(projectIdList, permissionIdList);
//    }


    /**
     * 根据权限list 生成权限树
     *
     * @param permissions
     * @return
     */
    public List<PermissionDTO> generateTree(List<Permission> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            return Collections.emptyList();
        }
        permissions.removeAll(Collections.singleton(null));
        // 去重
        permissions = permissions.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Permission::getId))), ArrayList::new));
        List<Integer> collect = permissions.stream().map(i -> i.getAppId()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(collect)){
            log.warn("权限关联的app为空");
            return Collections.emptyList();
        }
        Map<Integer, App> appMap = appService.listByIds(collect).stream().collect(Collectors.toMap(App::getId, Function.identity()));
        List<PermissionDTO> top = permissions.stream().filter(p -> 1 == p.getLevel()).map(p -> {
            App app = appMap.get(p.getAppId());
            Integer appKeyId = app.getId();
            PermissionDTO d = new PermissionDTO();
            BeanUtils.copyProperties(p, d);
            if (p.getAppId().equals(appKeyId)) {
                d.setAppIdStr(app.getAppId());
            }
            return d;
        }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(top)) {
            return Collections.emptyList();
        }
        permissions = permissions.stream().filter(i -> null != i.getParentId()).collect(Collectors.toList());
        //顶级菜单排序
        top = top.stream().sorted(Comparator.comparing(PermissionDTO::getSortNum)).collect(Collectors.toList());
        for (PermissionDTO p : top) {
            p.setChildren(generateChild(permissions, p.getId()));
        }
        return top;
    }


    /**
     * 填充权限的子节点数据
     *
     * @param permissions
     * @param id
     * @return
     */
    private static List<PermissionDTO> generateChild(List<Permission> permissions, Integer id) {
        if (permissions.isEmpty()) {
            return Collections.emptyList();
        }
        List<PermissionDTO> permissionChildList = permissions.stream().filter(i -> i.getParentId().intValue() == id).map(p -> {
            PermissionDTO d = new PermissionDTO();
            d.setId(p.getId());
            d.setType(p.getType());
            d.setAppId(p.getAppId());
            d.setParentId(id);
            d.setIsDeleted(p.getIsDeleted());
            d.setDefaultShow(p.getDefaultShow());
            d.setName(p.getName());
            d.setRemark(p.getRemark());
            d.setMenuType(p.getMenuType());
            d.setChildren(generateChild(permissions, p.getId()));
            d.setCode(p.getCode());
            d.setIsHidden(p.getIsHidden());
            d.setLevel(p.getLevel());
            d.setIconUrl(p.getIconUrl());
            d.setMenuUrl(p.getMenuUrl());
            d.setSortNum(p.getSortNum());
            d.setDefaultSelect(p.getDefaultSelect());
            d.setIsEmbed(p.getIsEmbed());
            d.setExtendz(p.getExtendz());
            d.setAppTheme(p.getAppTheme());
            d.setHomeFlag(p.getHomeFlag());
            return d;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(permissionChildList)) {
            List<PermissionDTO> resultList = null;
            try {
                resultList = permissionChildList.stream().sorted(Comparator.comparing(PermissionDTO::getSortNum)).collect(Collectors.toList());
            } catch (Exception e) {
                log.warn("权限排序出错 ======" + JSONObject.toJSONString(permissionChildList));
                return permissionChildList;
            }
            return resultList;
        }
        return permissionChildList;
    }


    /**
     * 根据项目id获取权限list
     *
     * @param projectId
     * @return
     */
    @Override
    public List<Permission> getListByProjectId(List<Integer> excludeIds, Integer projectId) {
        List<Integer> permissionIdList = projectPermissionService.list(Arrays.asList(projectId));
        if (CollectionUtils.isEmpty(permissionIdList)) {
            return Collections.emptyList();
        }
        PermissionQuery permissionQuery = new PermissionQuery();
        permissionQuery.setIdList(permissionIdList);
        if (!CollectionUtils.isEmpty(excludeIds)) {
            permissionQuery.setExcludeIdList(excludeIds);
        }
        return getPermissionList(permissionQuery);
    }

    /**
     * 根据企业id获取权限list
     *
     * @param enterpriseId
     * @deprecated 最好用 getEnterprisePermissions() 代替
     * @return
     */
    @Override
    @Deprecated
    public List<Permission> getListByEnterpriseId(List<Integer> excludeIds, Integer enterpriseId) {
        List<Integer> permissionIdList = enterprisePermissionService.list(Arrays.asList(enterpriseId));
        if (CollectionUtils.isEmpty(permissionIdList)) {
            return Collections.emptyList();
        }
        PermissionQuery permissionQuery = new PermissionQuery();
        permissionQuery.setIdList(permissionIdList);
        if (!CollectionUtils.isEmpty(excludeIds)) {
            permissionQuery.setExcludeIdList(excludeIds);
        }
        return getPermissionList(permissionQuery);
    }


    @Override
    public List<AppPermissionMenuDTO> getTreeListByIndustryId(Short industryId) {
        PermissionQuery permissionQuery = new PermissionQuery();
        permissionQuery.setIndustryId(industryId);
        List<Permission> permissions = getPermissionList(permissionQuery);
        List<AppPermissionMenuDTO> treeList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(permissions)) {
            List<PermissionDTO> permissionTrees = generateTree(permissions);
            treeList = getPermissionTreeGroupByApp(permissionTrees);
        }
        return treeList;
    }


    /**
     * 根据角色id获取权限Permission
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Permission> getListByRoleId(String appId, Integer roleId) {
        PermissionQuery permissionRoleQuery = new PermissionQuery();
        Role role = roleService.getRoleById(roleId);
        //超管 拼接全部权限码
        if(null != role.getGrade() && null != role.getType()){
            if(BusinessType.INDUSTRY.getCode() == role.getGrade() && RoleTypeEnum.SUPPER_MANAGER.getCode() == role.getType()){
                return getPermissionList(permissionRoleQuery);
            }
        }
        List<Integer> permissionIdList = rolePermissionService.getPermissionIdByRoleId(Arrays.asList(roleId));
        if (CollectionUtils.isEmpty(permissionIdList)) {
            return Collections.emptyList();
        }
        permissionRoleQuery.setIdList(permissionIdList);
        List<Permission> permissionList = getPermissionList(permissionRoleQuery);

        if (StringUtils.isNotEmpty(appId)) {
            App app = appService.getByAppId(appId);
            if (null == app) {
                log.info("根据appId获取app信息异常，查找不到，appId={}", appId);
                return Collections.emptyList();
            }
            Integer appKeyId = app.getId();
            List<Permission> permissionListByApp = new ArrayList<>();
            for (Permission permission : permissionList) {
                if (appKeyId.equals(permission.getAppId())) {
                    permissionListByApp.add(permission);
                }
            }
            return permissionListByApp;
        }

        return permissionList;
    }


    /**
     * 删除权限
     *
     * @param permissionIdList
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson deletePermission(List<Integer> permissionIdList) {
        try {
            //权限 数据
            permissionDao.deleteBatchIds(permissionIdList);
            //项目 权限
            projectPermissionService.deleteProjectPermission(null, permissionIdList);
            //企业 权限
            enterprisePermissionService.deleteEnterprisePermission(null, permissionIdList);
            //角色 权限
            rolePermissionService.deleteRolePermission(null, permissionIdList);
            // 删除接口权限控制
            //permissionAuthService.delete(permissionIdList);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultJson.fail("删除失败");
        }
        return ResultJson.success("删除成功");
    }


    /**
     * 插入 权限码（查重）   业态、appId、code 不能同时相同
     *
     * @param industryId
     * @param appIdPrimaryKey
     * @param code
     * @return
     */
    public Boolean permissionCodeExistChecking(String sceneCode, Integer appIdPrimaryKey, String code) {
        PermissionQuery permissionQuery = new PermissionQuery();
        //permissionQuery.setIndustryId(industryId);
        permissionQuery.setSceneCode(sceneCode);
        permissionQuery.setAppIdPrimaryKey(appIdPrimaryKey);
        permissionQuery.setCode(code);
        List<Permission> permissionList = getPermissionList(permissionQuery);
        if (CollectionUtils.isEmpty(permissionList)) {
            return false;
        }
        return true;
    }

    /**
     * 根据菜单权限id获取按钮
     *
     * @param permissionIdList
     * @return
     */
    @Override
    public List<Integer> findButtonIdByMenuId(List<Integer> permissionIdList) {
        if (permissionIdList.isEmpty()) {
            return Collections.emptyList();
        }
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.in("parent_id", permissionIdList);
        queryWrapper.eq("menu_type", MenuTypeEnum.BUTTON.getCode());
        List<Permission> permissions = permissionDao.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(permissions)) {
            return Collections.emptyList();
        }
        return permissions.stream().map(Permission::getId).collect(Collectors.toList());
    }

    /**
     * 获取当前账号的企业权限信息
     *
     * @param account
     * @return
     */
    @Override
    public List<Permission> getEnPermissionByAccount(Account account) {
        List<Permission> permissionList = new ArrayList<>();
        //企业权限
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.eq("account_id", account.getId());
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        List<Integer> enterpriseIdList = accountOrganizations.stream().map(e -> e.getEnterpriseId()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(enterpriseIdList)) {
            log.warn("该帐号 {} {} 没有关联企业", account.getLoginName(), account.getName());
            return permissionList;
        }
        List<Integer> permissionIdList = enterprisePermissionService.list(enterpriseIdList);
        PermissionQuery permissionEnterpriseQuery = new PermissionQuery();
        permissionEnterpriseQuery.setIdList(permissionIdList);
        permissionEnterpriseQuery.setOrderColumn("sort_num");
        permissionEnterpriseQuery.setOrderAsc(false);
        return getPermissionList(permissionEnterpriseQuery);
    }

    /**
     * 获取当前账号的项目权限信息
     *
     * @param account
     * @return
     */
    @Override
    public List<Permission> getProPermissionByAccount(Account account) {
        List<Permission> permissionList = new ArrayList<>();
        List<Integer> projectIdList = accountProjectService.list(account.getId(), null);
        if (CollectionUtils.isEmpty(projectIdList)) {
            log.warn("该人员 {} {} 暂未关联项目信息", account.getLoginName(), account.getName());
            return permissionList;
        }
        List<Integer> projectPermissionList = projectPermissionService.list(projectIdList);
        if (CollectionUtils.isEmpty(projectPermissionList)) {
            log.warn("该项目 {} 暂未关联权限信息", projectIdList.get(0));
            return permissionList;
        }
        PermissionQuery permissionProjectQuery = new PermissionQuery();
        permissionProjectQuery.setIdList(projectPermissionList);
        permissionProjectQuery.setOrderColumn("sort_num");
        permissionProjectQuery.setOrderAsc(false);
        return getPermissionList(permissionProjectQuery);
    }

    /**
     * 获取当前账号的角色权限信息
     *
     * @param account
     * @return
     */
    @Override
    public List<Permission> getRolePermissionByAccount(Integer projectId, Account account, App app) {
        List<Permission> permissionList = new ArrayList<>();
        List<Integer> roleIdList = accountRoleService.findRoleIdByAccountId(account.getId());
        List<Integer> commonInitializedRoles = roleService.getCommonInitializedRoles(null);
        Boolean containsCommonInitializedRole = false;

        //包含业态级别的普通内置角色，需要额外兼容获取项目的菜单
        for (Integer roleId : commonInitializedRoles) {
            if (roleIdList.contains(roleId)) {
                containsCommonInitializedRole = true;
            }
        }
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id", roleIdList);
        List<Role> roleList = roleService.list(roleQueryWrapper);
        List<Integer> roleIdResult = new ArrayList<>();
        for (Role role : roleList) {
            if (null != role.getProjectId()) {
                if (role.getProjectId().equals(projectId)) {
                    roleIdResult.add(role.getId());
                }
            } else {
                roleIdResult.add(role.getId());
            }
        }
        if (CollectionUtils.isEmpty(roleIdResult)) {
            log.warn("该人员 {} {} 暂未关联角色信息", account.getLoginName(), account.getName());
            return permissionList;
        }
        List<Integer> rolePermissionList = rolePermissionService.getPermissionIdByRoleId(roleIdResult);

        //如果是包含业态普通内置角色，那么需要取当前选中的项目id权限 作为并集
        if (containsCommonInitializedRole) {
            if (null != app) {
                if (AppTypeEnum.APP.getType() == app.getAppType() || AppTypeEnum.MINI_PROGRAM.getType() == app.getAppType() ) {
                    if (null != projectId) {
                        ParamConfigCriteria privateConfigCriteria=new ParamConfigCriteria();
                        privateConfigCriteria.withCode(Constant.OWNER_APP);
                        privateConfigCriteria.withBusinessType(BusinessType.INDUSTRY);
                        privateConfigCriteria.withBuzId(Integer.valueOf(app.getIndustryId()));
                        ParameterConfig ownerAppConfig = parameterConfigService.findByCriteria(privateConfigCriteria);
                        if (null!=ownerAppConfig){
                            JSONObject  propertyObject= JSON.parseObject(ownerAppConfig.getValue());
                            List<String> ownerAppIdList = (List<String>) propertyObject.get("appId");
                            if (!CollectionUtils.isEmpty(ownerAppIdList)){
                                if (ownerAppIdList.contains(app.getAppId())){
                                    List<Integer> projectPermissionList = projectPermissionService.list(Arrays.asList(projectId));
                                    rolePermissionList.addAll(projectPermissionList);
                                }
                            }
                        }

                    }
                }
            }
        }

        if (CollectionUtils.isEmpty(rolePermissionList)) {
            log.warn("该帐号仅有内置角色或者无角色关联，除默认展示权限外，暂无额外的菜单权限,账号名={}，账号id={}", account.getLoginName(), account.getId());
            return permissionList;
        }

        PermissionQuery permissionRoleQuery = new PermissionQuery();
        permissionRoleQuery.setIdList(rolePermissionList);
        permissionRoleQuery.setOrderColumn("sort_num");
        permissionRoleQuery.setOrderAsc(false);
        return  getPermissionList(permissionRoleQuery);
    }

	@Override
    @Transactional
	public ResultJson adminBatchCreate(List<Permission> permissions) {
    	log.info("批量创建权限");
    	if(CollectionUtils.isEmpty(permissions)){
    		return ResultJson.fail("空集合");
		}
        String appIdStr1 = permissions.get(0).getAppIdStr();
    	if(StringUtils.isEmpty(appIdStr1)){
    	    return ResultJson.fail("缺少app信息");
        }
        App app = appService.getByAppId(appIdStr1);
    	QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        queryWrapper.eq("app_id", app.getId());
        List<Permission> permissions1 = permissionDao.selectList(queryWrapper);

        if(!permissions1.isEmpty()){
            return ResultJson.fail("当前app已经存在菜单");
        }
        List<Permission> createList = new ArrayList<>();
        for (Permission permission : permissions) {
            if(StringUtils.isEmpty(permission.getName())){
                log.warn("权限批量创建缺少权限名称");
                continue;
            }
            if(StringUtils.isEmpty(permission.getCode())){
                log.warn("缺少编码");
                continue;
            }
            if(StringUtils.isEmpty(permission.getSceneCode())){
                log.warn("缺少场景编码");
                continue;
            }else{
                QueryWrapper<SceneApp> sceneAppQueryWrapper = new QueryWrapper<>();
                sceneAppQueryWrapper.eq("app_code", app.getCode());
                sceneAppQueryWrapper.eq("scene_code",permission.getSceneCode());
                List<SceneApp> sceneApps = sceneAppDao.selectList(sceneAppQueryWrapper);
                if(CollectionUtils.isEmpty(sceneApps)){
                    log.warn("应用与场景不匹配");
                    continue;
                }
            }
            if(StringUtils.isEmpty(permission.getAppIdStr())){
                log.warn("缺少appId");
                continue;
            }
            if(null == permission.getLevel()){
                log.warn("缺少层级");
                continue;
            }
            if(null == permission.getMenuType()){
                return ResultJson.fail("缺少菜单类型");
            }
            permission.setAppId(app.getId());
            permission.setIndustryId(app.getIndustryId());
            createList.add(permission);
        }
        List<Permission> level1 = createList.stream().filter(i -> (null != i.getLevel() && i.getLevel().equals(1))).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(level1)){
            return ResultJson.fail("缺少一级菜单");
        }
        Integer dbIndex = permissionDao.autoIncr();
        List<Integer> levels = createList.stream().map(j -> j.getLevel()).distinct().sorted().collect(Collectors.toList());
        Map<Integer, Integer> originNew = new HashMap<>();
        for (Integer level : levels) {
            List<Permission> currentLevel = createList.stream().filter(i -> i.getLevel().equals(level)).collect(Collectors.toList());
            for (Permission permission : currentLevel) {
                if(1 == level){
                    originNew.put(permission.getId(), dbIndex);
                    permission.setId(dbIndex);
                    permission.setParentId(0);
                }else{
                    originNew.put(permission.getId(), dbIndex);
                    permission.setId(dbIndex);
                    permission.setParentId(originNew.get(permission.getParentId()));
                }
                dbIndex ++;
            }
        }
//        saveBatch(createList);
        permissionDao.batchInsert(createList);
		return ResultJson.success();
	}

    @Override
    public Integer autoIncr() {
        return permissionDao.autoIncr();
    }

    @Override
    public List<PermissionDTO> getAdminAccountPermissionTree(AdminAccount adminAccount, App app) {
        QueryWrapper<AdminAccountRole> adminAccountRoleQueryWrapper = new QueryWrapper<>();
        adminAccountRoleQueryWrapper.eq("admin_account_id", adminAccount.getId());
        List<AdminAccountRole> list = adminAccountRoleService.list(adminAccountRoleQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
            throw new DataException("获取角色信息失败");
        }
        List<Integer> collect = list.stream().map(i -> i.getRoleId()).collect(Collectors.toList());
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id", collect);
        roleQueryWrapper.eq("is_deleted", false);
        List<Role> list1 = roleService.list(roleQueryWrapper);
        if(CollectionUtils.isEmpty(list1)){
            throw new DataException("角色信息不存在");
        }
        // 根据角色获取权限
        List<Permission> permissions = rolePermissionService.getPermissionByRoleId(list1.stream().map(i -> i.getId()).collect(Collectors.toList()));
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.select("id");
        permissionQueryWrapper.eq("app_id", app.getId());
        List<Permission> permissions1 = permissionDao.selectList(permissionQueryWrapper);
        if(permissions1.isEmpty()){
            log.warn("当前app {}  没有权限信息", app.getId());
            return Collections.emptyList();
        }
        List<Integer> collect1 = permissions1.stream().map(i -> i.getId()).collect(Collectors.toList());
        permissions = permissions.stream().filter(i -> collect1.contains(i.getId())).collect(Collectors.toList());
        return generateTree(permissions);
    }

    @Override
    public List<AppPermissionMenuDTO> getPermissionTreeAdmin(PermissionTreeDTO permissionTreeDTO) {
        List<Permission> permissions = null;
        if (Objects.nonNull(permissionTreeDTO.getProjectId())) {
            permissions = getListByProjectId(permissionTreeDTO.getExcludeIds(), permissionTreeDTO.getProjectId());
        } else if (Objects.nonNull(permissionTreeDTO.getEnterpriseId())) {
            permissions = getEnterprisePermissions(permissionTreeDTO);
        } else {
            permissions = permissionQueryHandler(permissionTreeDTO);
        }
        if (CollectionUtils.isEmpty(permissions)) {
            log.info("未查询到权限 {}", JSONObject.toJSONString(permissionTreeDTO));
            return Collections.emptyList();
        }
        // 去除掉非项目范围权限
        if(null != permissionTreeDTO.getPermissionType()){
            permissions = permissions.stream().filter(i -> null == i.getType() || i.getType().equals(permissionTreeDTO.getPermissionType().type)).collect(Collectors.toList());
        }
        List<PermissionDTO> permissionDTOS = generateTree(permissions);

        List<Permission> sort = permissions.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList());
        // 项目权限范围选择的那里不需要裁剪
        if(PermissionTypeEnum.PROJECT == permissionTreeDTO.getPermissionType()){
            if(null != permissionTreeDTO.getProjectId() || null != permissionTreeDTO.getEnterpriseId()){
                for (int i = 0; i < sort.get(0).getLevel(); i ++){
                    projectPermissionTreeCut(permissionDTOS);
                }
            }
        }
        return getPermissionTreeGroupByApp(permissionDTOS);
    }

    /**
     * 裁剪掉最下级没有项目范围权限的上级菜单
     * @param permissions
     */
    private void projectPermissionTreeCut(List<PermissionDTO> permissions) {
        if(CollectionUtils.isEmpty(permissions)){
            return ;
        }
        Iterator<PermissionDTO> iterator = permissions.iterator();
        while (iterator.hasNext()){
            PermissionDTO pop = iterator.next();
            if(pop.hasChild()){
                projectPermissionTreeCut(pop.getChildren());
                // 3 企业类型
            }else if(null == pop.getType() || 3 == pop.getType()){
                // 移除
                iterator.remove();
            }
        }
    }

    /**
     * 获取企业的权限
     * @param permissionTreeDTO
     * @return
     */
    private List<Permission> getEnterprisePermissions(PermissionTreeDTO permissionTreeDTO){
        List<Integer> permissionIdList = enterprisePermissionService.list(Arrays.asList(permissionTreeDTO.getEnterpriseId()));
        if (CollectionUtils.isEmpty(permissionIdList)) {
            return Collections.emptyList();
        }
        PermissionQuery permissionQuery = new PermissionQuery();
        permissionQuery.setIdList(permissionIdList);
        if(null != permissionTreeDTO.getNeedButton()){
            permissionQuery.setMenuType(permissionTreeDTO.getNeedButton() ? (short)0 : (short)1);
        }
        if (!CollectionUtils.isEmpty(permissionTreeDTO.getExcludeIds())) {
            permissionQuery.setExcludeIdList(permissionTreeDTO.getExcludeIds());
        }
        if(null != permissionTreeDTO.getPermissionType()){
            permissionQuery.setType(permissionTreeDTO.getPermissionType().getCode());
        }
        if(!CollectionUtils.isEmpty(permissionTreeDTO.getMenuTypes())){
            permissionQuery.setMenuTypes(permissionTreeDTO.getMenuTypes());
        }
        return getPermissionList(permissionQuery);
    }

    /**
     * permissionTreeDTO 转换成 permissionQuery 查询
     * @param permissionTreeDTO
     * @return
     */
    private List<Permission> permissionQueryHandler(PermissionTreeDTO permissionTreeDTO){
        PermissionQuery permissionQuery = new PermissionQuery();
        if(null != permissionTreeDTO.getType()){
            permissionQuery.setType(permissionTreeDTO.getType());
        }
        if(null != permissionTreeDTO.getSceneCode()){
            permissionQuery.setSceneCode(permissionTreeDTO.getSceneCode());
        }
        if(null != permissionTreeDTO.getAppId()){
            permissionQuery.setAppIdPrimaryKey(permissionTreeDTO.getAppId());
        }
        boolean flag = false;
        if(StringUtils.isNotEmpty(permissionTreeDTO.getAppIdStr())){
            App app = appService.getByAppId(permissionTreeDTO.getAppIdStr());
            if (app.getAppType().equals(AppTypeEnum.SYSTEM.getType())) {
                flag = true;
            }
            permissionQuery.setAppIdPrimaryKey(app.getId());
        }
        if(null != permissionTreeDTO.getIndustryId()){ // 平台粒度小于开发者 所有有平台就不用筛选开发者了
            QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
            appQueryWrapper.eq("industry_id", permissionTreeDTO.getIndustryId());
            List<App> list = appService.list(appQueryWrapper);
            if(list.isEmpty()){
                permissionQuery.setAppIds(Arrays.asList(-1));
            }else{
                permissionQuery.setAppIds(list.stream().map(i -> i.getId()).collect(Collectors.toList()));
            }
        }else if(null != permissionTreeDTO.getDevelopId()){
            QueryWrapper<App> appQueryWrapper = new QueryWrapper<>();
            appQueryWrapper.select("id");
            appQueryWrapper.eq("develop_id", permissionTreeDTO.getDevelopId());
            List<App> apps = appDao.selectList(appQueryWrapper);
            // 过滤APP类型为系统的应用
            if (!CollectionUtils.isEmpty(apps) && !flag) {
                List<App> appsDb = appService.listByIds(apps.stream().map(App::getId).collect(Collectors.toList()));
                apps = appsDb.stream().filter(app -> !app.getAppType().equals(AppTypeEnum.SYSTEM.getType())).collect(Collectors.toList());
            }
            if(apps.isEmpty()){
                log.warn("开发者 {} 暂无应用", permissionTreeDTO.getDevelopId());
                permissionQuery.setAppId("-1");
            }else{
                permissionQuery.setAppIds(apps.stream().map(i -> i.getId()).collect(Collectors.toList()));
            }
        }
        //场景关联的app
        if(null != permissionTreeDTO.getSceneCode()){
            List<Integer> ids = sceneAppDao.findAppIds(permissionTreeDTO.getSceneCode());
            if(!CollectionUtils.isEmpty(ids)) {
                if(null != permissionTreeDTO.getDevelopId()){
                    //有开发者id
                    if("-1".equals(permissionQuery.getAppId())){
                        //不做处理
                    }else{
                        //取交集
                        ids.retainAll(permissionQuery.getAppIds());
                        if(CollectionUtils.isEmpty(ids)) {
                            log.warn("开发者 {},场景 {} 暂无应用", permissionTreeDTO.getDevelopId(),permissionTreeDTO.getSceneId());
                            permissionQuery.setAppId("-1");
                        }else{
                            permissionQuery.setAppIds(ids);
                        }
                    }
                }else{
                    //没有开发者id过滤直接赋值
                    if(CollectionUtils.isEmpty(ids)) {
                        log.warn("场景 {} 暂无应用", permissionTreeDTO.getSceneId());
                        permissionQuery.setAppId("-1");
                    }else{
                        permissionQuery.setAppIds(ids);
                    }
                }
            }else{
                log.warn("场景 {} 暂无应用", permissionTreeDTO.getSceneId());
                permissionQuery.setAppId("-1");
            }
        }
        if(null != permissionTreeDTO.getNeedButton()){
            permissionQuery.setMenuType(permissionTreeDTO.getNeedButton() ? (short)0 : (short)1);
        }
        if (!CollectionUtils.isEmpty(permissionTreeDTO.getExcludeIds())) {
            permissionQuery.setExcludeIdList(permissionTreeDTO.getExcludeIds());
            return getPermissionList(permissionQuery);
        } else {
            return getPermissionList(permissionQuery);
        }
    }

    @Override
    public List<PermissionDTO> getPermissionFromGroup(PermissionQuery permissionQuery) {
        List<Permission> finalPermission = getPermissions(permissionQuery);
        // 只展示当前app下的权限
        App app = appService.getByAppId(permissionQuery.getAppId());
        List<PermissionDTO> permissionDTOS = generateTree(finalPermission.stream().filter(i -> i.getAppId().equals(app.getId())).collect(Collectors.toList()));
        if(permissionDTOS.isEmpty()){
            return permissionDTOS;
        }
        Permission permission = finalPermission.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList()).get(0);
        for (int i = 0; i < permission.getLevel(); i ++){
            permissionCut(permissionDTOS);
        }
        return permissionDTOS;
    }

    /**
     * 通过权限组获取权限
     * @param permissionQuery
     * @return
     */
    private List<Permission> getPermissions(PermissionQuery permissionQuery){
        if(null == permissionQuery.getAccountId()){
            log.warn("缺少帐号信息");
            return Collections.emptyList();
        }

        QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
        permissionGroupQueryWrapper.eq("account_id", permissionQuery.getAccountId());
        List<PermissionGroup> list = permissionGroupService.list(permissionGroupQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
            log.warn("该帐号 {} 没有权限组信息", permissionQuery.getAccountId());
            return Collections.emptyList();
        }

        List<Integer> roleIds = new ArrayList<>();
        List<Integer> projectIds = new ArrayList<>();
        List<PermissionGroupDTO> permissionGroupDTOS = new ArrayList<>(list.size());
        // 遍历 把，分割的String 转为 list
        for (PermissionGroup permissionGroup : list) {
            PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
            BeanUtils.copyProperties(permissionGroup, permissionGroupDTO);
            List<Integer> roleId1 = Arrays.stream(permissionGroup.getRoleIds().split(",")).map(i -> Integer.valueOf(i)).collect(Collectors.toList());
            roleIds.addAll(roleId1);
            permissionGroupDTO.setRoleList(roleId1);
            String s = permissionGroup.getProjectIds();
            if(StringUtils.isNotEmpty(s)){
                List<Integer> projectId1 = Arrays.stream(s.split(",")).map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                projectIds.addAll(projectId1);
                permissionGroupDTO.setProjectList(projectId1);
            }
            permissionGroupDTOS.add(permissionGroupDTO);
        }

        // 将数据库里的权限组转成对象
        permissionGroupDataWrapper(permissionGroupDTOS, roleIds);
        List<Integer> choseRoles = new ArrayList<>();

        // 根据权限组获取权限 step1 选择权限组，step2 计算权限结果
        // 1 选择权限组 根据企业和业态筛选出符合的权限组
        List<PermissionGroupDTO> filterGroup = getPermissionGroup(permissionGroupDTOS, choseRoles, permissionQuery);
        if(filterGroup.isEmpty()){
            return Collections.emptyList();
        }

        // 2 计算权限
        // 企业权限和角色权限取交集
        List<Permission> entAndRole = getPermissionEntAndRole(permissionQuery.getEnterpriseId(), choseRoles);
        List<Permission> finalPermission = new ArrayList<>();
        // 有选项目选择器
        if(null != permissionQuery.getProjectId()){
            List<ProjectPermission> list1 = getProjectPermission(permissionQuery.getProjectId(), permissionQuery.getEnterpriseId());
            if(!list1.isEmpty()){
                List<Integer> projectPermission = list1.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
                RoleTypeDTO roleTypeDTO = roleService.getAccountRoleType(permissionQuery.getAccountId());
                if(RoleTypeEnum.TOURIST == roleTypeDTO.getRoleTypeEnum()){
                    finalPermission = entAndRole.stream().filter(i -> {
                        // 项目权限取交集
                        if (null == i.getType()){
                            return true;
                        } else if (2 == i.getType()){
                            //与项目权限取交集
                            return projectPermission.contains(i.getId());
                        } else {
                            return true;
                        }
                    }).collect(Collectors.toList());;
                    return finalPermission;
                }
                // 权限组取完后的权限
                List<Permission> permissions = permissionGroupAlgorithm(filterGroup, permissionQuery, roleIds, projectIds);
                List<Integer> pId = permissions.stream().map(i -> i.getId()).collect(Collectors.toList());
                finalPermission = entAndRole.stream().filter(i -> {
                    // 项目权限取交集
                    if (null == i.getType()){
                        return true;
                    } else if (2 == i.getType()){
                        // 与权限组取交集 && 与项目权限取交集
                        return pId.contains(i.getId()) && projectPermission.contains(i.getId());
                    } else {
                        return true;
                    }
                }).collect(Collectors.toList());
            }
        }else{
            // 过滤掉项目权限
            finalPermission = entAndRole.stream().filter(i -> null == i.getType() || i.getType() != 2).collect(Collectors.toList());
        }
        return finalPermission;
    }


    private List<PermissionGroupDTO> getPermissionGroup(List<PermissionGroupDTO> permissionGroupDTOS, List<Integer> choseRoles, PermissionQuery permissionQuery){
        List<PermissionGroupDTO> filterGroup = new ArrayList<>();
        for (PermissionGroupDTO permissionGroupDTO : permissionGroupDTOS) {
            List<Role> roles = permissionGroupDTO.getRoles().stream()
                        .filter(i -> (i.getGrade() == 2) || (i.getGrade() == 1 && i.getEnterpriseId().equals(permissionQuery.getEnterpriseId()))).collect(Collectors.toList());
            if(!roles.isEmpty()){
                log.info("当前取权限组角色为 {}", permissionGroupDTO.getRoleIds());
                choseRoles.addAll(permissionGroupDTO.getRoleList());
                filterGroup.add(permissionGroupDTO);
            }
        }
        return filterGroup;
    }

    /**
     * 裁切
     * 裁切掉下级没用企业or项目级菜单的结点
     * @param permissions
     */
    private void permissionCut(List<PermissionDTO> permissions) {
        if(CollectionUtils.isEmpty(permissions)){
            return ;
        }
        Iterator<PermissionDTO> iterator = permissions.iterator();
        while (iterator.hasNext()){
            PermissionDTO pop = iterator.next();
            if(pop.hasChild()){
                permissionCut(pop.getChildren());
                // 既不是企业级也不是项目级  并且 菜单类型不为页面的 并且 不是按钮
            }else if(null == pop.getType() && 1 != pop.getMenuType() && 0 != pop.getMenuType()){
                // 移除
                iterator.remove();
            }
        }
    }

    /**
     * 企业权限和角色取交集
     * @param enterpriseId
     * @param roleIds
     * @return
     */
    private List<Permission> getPermissionEntAndRole(Integer enterpriseId, List<Integer> roleIds){
        if(CollectionUtils.isEmpty(roleIds)){
            log.warn("角色集合为空");
            return Collections.emptyList();
        }
        QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
        enterprisePermissionQueryWrapper.eq("enterprise_id", enterpriseId);
        List<EnterprisePermission> list = enterprisePermissionService.list(enterprisePermissionQueryWrapper);
        List<Integer> enterprisePermissionIds = list.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());

        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.in("role_id", roleIds);
        List<RolePermission> list1 = rolePermissionService.list(rolePermissionQueryWrapper);
        List<Integer> rolePermissionIds = list1.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
        // 兼容开放平台 既没有企业也没有项目
        if(null == enterpriseId){
            return permissionDao.selectBatchIds(rolePermissionIds);
        }
        Collection<Integer> intersection = org.apache.commons.collections4.CollectionUtils.intersection(enterprisePermissionIds, rolePermissionIds);
        if(CollectionUtils.isEmpty(intersection)){
            return Collections.emptyList();
        }
        return permissionDao.selectBatchIds(intersection);
    }

    /**
     * 企业和项目权限取交集
     * @deprecated 已废弃
     * @param permissionQuery
     * @return
     */
    private List<Permission> getPermissionFromEntAndProject(PermissionQuery permissionQuery) {
        List<Permission> enterprisePermissions = new ArrayList<>();
        // 获取企业权限
        if(null != permissionQuery.getEnterpriseId()){
            enterprisePermissions = this.getListByEnterpriseId(null, permissionQuery.getEnterpriseId());
        }
        // 没选项目的时候不展示项目范围权限
        if(null == permissionQuery.getProjectId() && !CollectionUtils.isEmpty(enterprisePermissions)){
            enterprisePermissions = enterprisePermissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
        }else{
            // 选了项目过滤掉项目的权限
            QueryWrapper<ProjectPermission> projectPermissionQueryWrapper = new QueryWrapper<>();
            projectPermissionQueryWrapper.eq("project_id", permissionQuery.getProjectId());
            List<ProjectPermission> list1 = projectPermissionService.list(projectPermissionQueryWrapper);
            if(!list1.isEmpty()){
                List<Integer> collect = list1.stream().map(i -> i.getPermissionId()).collect(Collectors.toList());
                // 过滤掉当前项目不包含的权限
                enterprisePermissions = enterprisePermissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type || collect.contains(i.getId())).collect(Collectors.toList());
            }else{
                // 去掉所有的项目级权限
                enterprisePermissions = enterprisePermissions.stream().filter(i -> i.getType() != PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
            }
        }
        return enterprisePermissions;
    }

    /**
     * 权限组数据填充 string转成list 填充角色对象
     * @param list
     * @return
     */
    private void permissionGroupDataWrapper(List<PermissionGroupDTO> list, List<Integer> roleIds){

        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.in("id", roleIds.stream().distinct().collect(Collectors.toList()));
        List<Role> list2 = roleService.list(roleQueryWrapper);
        Map<Integer, Role> roleMap = list2.stream().collect(Collectors.toMap(Role::getId, Function.identity()));

        for (PermissionGroupDTO permissionGroupDTO : list) {
            List<Integer> roleList = permissionGroupDTO.getRoleList();
            List<Role> collect = roleList.stream().map(i -> roleMap.get(i)).collect(Collectors.toList());
            permissionGroupDTO.setRoles(collect);
        }
    }

    @Override
    public List<AppPermissionMenuDTO> getPermissionTree(PermissionTreeDTO permissionTreeDTO) {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        if(!CollectionUtils.isEmpty(permissionTreeDTO.getIds())){
            permissionQueryWrapper.in("id", permissionTreeDTO.getIds());
        }
        if(null != permissionTreeDTO.getIndustryId()){
            permissionQueryWrapper.eq("industry_id", permissionTreeDTO.getIndustryId());
        }
        List<Permission> permissions = permissionDao.selectList(permissionQueryWrapper);
        return getPermissionTreeGroupByApp(generateTree(permissions));
    }

    @Override
    public List<Permission> getParent(List<Integer> permissionIds) {
        List<Permission> resultList = new ArrayList<>();
        List<Permission> permissionList = permissionDao.selectBatchIds(permissionIds);
        for (Permission permission : permissionList) {
            if (null != permission.getParentId() || permission.getParentId() > 0) {
                resultList.addAll(getParent(Arrays.asList(permission.getParentId())));
            }
        }
        permissionList.addAll(resultList);
        List<Permission> collect = permissionList.stream().distinct().collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<PermissionDTO> getPermissionTreeByRole(Role role) {
        List<Permission> permissions = getListByRoleId(null,role.getId());
        return generateTree(permissions);
    }


    /**
     * 权限组获取权限算法
     * @param permissionGroupDTOS
     * @param permissionQuery
     * @param roleIds
     * @param projectIds
     * @return
     */
    private List<Permission> permissionGroupAlgorithm(List<PermissionGroupDTO> permissionGroupDTOS, PermissionQuery permissionQuery, List<Integer> roleIds, List<Integer> projectIds) {

        // 筛选出符合当前所选项目的权限组
        List<PermissionGroupDTO> permission = permissionGroupDTOS.stream().filter(i -> null != i.getProjectList() && i.getProjectList().contains(permissionQuery.getProjectId())).collect(Collectors.toList());

        List<Integer> allPermissions = new ArrayList<>();

        QueryWrapper<ProjectPermission> projectPermissionQueryWrapper = new QueryWrapper<>();
        projectPermissionQueryWrapper.select("permission_id", "project_id");
        List<Integer> collect = projectIds.stream().distinct().collect(Collectors.toList());
        if(collect.isEmpty()){
            log.info("权限组项目为空");
            return Collections.emptyList();
        }
        projectPermissionQueryWrapper.in("project_id", collect);
        List<ProjectPermission> projectPermissions = projectPermissionService.list(projectPermissionQueryWrapper);
        if(CollectionUtils.isEmpty(projectPermissions)){
            return Collections.emptyList();
        }
        // 项目权限map
        Map<Integer, List<Integer>> projectPermissionMap = projectPermissions.stream().collect(Collectors.groupingBy(ProjectPermission::getProjectId, Collectors.mapping(ProjectPermission::getPermissionId, Collectors.toList())));
        allPermissions.addAll(projectPermissions.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList()));
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.select("permission_id", "role_id");
        rolePermissionQueryWrapper.in("role_id", roleIds.stream().distinct().collect(Collectors.toList()));
        List<RolePermission> rolePermissions = rolePermissionService.list(rolePermissionQueryWrapper);

        // 角色权限map
        Map<Integer, List<Integer>> rolePermissionMap = rolePermissions.stream().collect(Collectors.groupingBy(RolePermission::getRoleId, Collectors.mapping(RolePermission::getPermissionId, Collectors.toList())));
        allPermissions.addAll(rolePermissions.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList()));

        List<Permission> finalCollect = new ArrayList<>();
        for (PermissionGroupDTO permissionGroupDTO : permission) {
            // 取交集 结果为项目范围权限
            permissionGroupHandler(permissionGroupDTO.getProjectList(), permissionGroupDTO.getRoleList(), finalCollect, projectPermissionMap, rolePermissionMap, permissionDao.selectBatchIds(allPermissions));
        }
        return finalCollect;
    }

    /**
     * 权限组取交集获取权限
     * @param projectIds1
     * @param roleIds1
     * @param finalCollect
     * @param projectPermissionMap
     * @param rolePermissionMap
     * @param permissions
     */
    private void permissionGroupHandler(List<Integer> projectIds1, List<Integer> roleIds1, List<Permission> finalCollect, Map<Integer, List<Integer>> projectPermissionMap, Map<Integer, List<Integer>> rolePermissionMap, List<Permission> permissions){
        // 项目权限
        List<Permission> projectPermission = new ArrayList<>();
        for (Integer integer : projectIds1) {
            List<Integer> integers = projectPermissionMap.get(integer);
            if(!CollectionUtils.isEmpty(integers)){
                List<Permission> collect2 = permissions.stream().filter(i -> integers.contains(i.getId())).collect(Collectors.toList());
                projectPermission.addAll(collect2);
            }
        }
        // 角色权限
        List<Permission> rolePermission = new ArrayList<>();
        for (Integer integer : roleIds1) {
            List<Integer> integers = rolePermissionMap.get(integer);
            if(!CollectionUtils.isEmpty(integers)){
                List<Permission> collect2 = permissions.stream().filter(i -> integers.contains(i.getId())).collect(Collectors.toList());
                rolePermission.addAll(collect2);
            }
        }

        // 对项目类型的权限取交集
        List<Permission> collect2 = rolePermission.stream().filter(i -> i.getType() == PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
        List<Permission> collect4 = projectPermission.stream().filter(i -> i.getType() == PermissionTypeEnum.PROJECT.type).collect(Collectors.toList());
        if(!collect4.isEmpty()){
            List<Integer> ids = collect4.stream().map(i -> i.getId()).collect(Collectors.toList());
            collect2 = collect2.stream().filter(i -> ids.contains(i.getId())).collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(Permission::getId))), ArrayList::new));
            if(!CollectionUtils.isEmpty(collect2)){
                finalCollect.addAll(collect2);
            }
        }
    }

    /**
     * 动态查询封装器生成
     *
     * @param permissionQuery
     * @return
     */
    private QueryWrapper<Permission> handleParams(PermissionQuery permissionQuery) {
        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("is_deleted", false);
        // 默认过滤无效应用app_id相关的菜单权限
        AppQuery appQuery = new AppQuery();
        appQuery.setStatus(0);
        List<App> list = appService.list(appQuery);
        if (!CollectionUtils.isEmpty(list)) {
            List<Integer> collect = list.stream().map(App::getId).collect(Collectors.toList());
            permissionQueryWrapper.notIn("app_id", collect);
        }
        if (null == permissionQuery) {
            return permissionQueryWrapper;
        }
        permissionQueryWrapper.orderBy(!org.springframework.util.StringUtils.isEmpty(permissionQuery.getOrderColumn()), permissionQuery.getOrderAsc(), permissionQuery.getOrderColumn());
        if (!CollectionUtils.isEmpty(permissionQuery.getSelectColumnList())) {
            String[] fieldNameArray = permissionQuery.getSelectColumnList().stream().toArray(String[]::new);
            permissionQueryWrapper.select(fieldNameArray);
        }
        if (!CollectionUtils.isEmpty(permissionQuery.getIdList())) {
            permissionQueryWrapper.in("id", permissionQuery.getIdList());
        }
        if (null != permissionQuery.getExcludeId()) {
            permissionQueryWrapper.ne("id", permissionQuery.getExcludeId());
        }
        if (!CollectionUtils.isEmpty(permissionQuery.getExcludeIdList())) {
            permissionQueryWrapper.notIn("id", permissionQuery.getExcludeIdList());
        }
        if (null != permissionQuery.getIndustryId()) {
            permissionQueryWrapper.eq("industry_id", permissionQuery.getIndustryId());
        }
        if (null != permissionQuery.getAppIdPrimaryKey()) {
            permissionQueryWrapper.eq("app_id", permissionQuery.getAppIdPrimaryKey());
        }
        /*if (StringUtils.isNotEmpty(permissionQuery.getSceneCode())) {
            permissionQueryWrapper.eq("scene_code", permissionQuery.getSceneCode());
        }*/
        if (null != permissionQuery.getNameOrParentId()) {
            permissionQueryWrapper.and(wrapper -> wrapper.eq("parent_id", permissionQuery.getNameOrParentId()).or().like("name",permissionQuery.getNameOrParentId()));
        }
        if(StringUtils.isNotEmpty(permissionQuery.getAppId())){
            App app = appService.getByAppId(permissionQuery.getAppId());
            if(app != null){
                permissionQueryWrapper.eq("app_id", app.getId());
            }else{
                permissionQueryWrapper.eq("app_id", -1);
            }
        }
        if (null != permissionQuery.getParentId()) {
            permissionQueryWrapper.eq("parent_id", permissionQuery.getParentId());
        }
        if (null != permissionQuery.getLevel()) {
            permissionQueryWrapper.eq("level", permissionQuery.getLevel());
        }
        if (StringUtils.isNotEmpty(permissionQuery.getName())) {
            permissionQueryWrapper.like("name", permissionQuery.getName());
        }
        if (StringUtils.isNotEmpty(permissionQuery.getCode())) {
            permissionQueryWrapper.eq("code", permissionQuery.getCode());
        }
        if (!CollectionUtils.isEmpty(permissionQuery.getCodes())) {
            permissionQueryWrapper.in("code", permissionQuery.getCodes());
        }
        if (StringUtils.isNotEmpty(permissionQuery.getSceneCode())) {
            String[] split = permissionQuery.getSceneCode().split(",");
            permissionQueryWrapper.in("scene_code", split);
        }
        if (null != permissionQuery.getMenuType()) {
            permissionQueryWrapper.eq("menu_type", permissionQuery.getMenuType());
        }
        if(!CollectionUtils.isEmpty(permissionQuery.getMenuTypes())){
            permissionQueryWrapper.in("menu_type", permissionQuery.getMenuTypes());
        }
        if(!CollectionUtils.isEmpty(permissionQuery.getAppIds())){
            permissionQueryWrapper.in("app_id", permissionQuery.getAppIds());
        }
        if(null != permissionQuery.getType()){
            permissionQueryWrapper.and(wrapper -> wrapper.eq("type", permissionQuery.getType()).or().isNull("type"));
        }
        return permissionQueryWrapper;
    }

    @Override
    public List<ScenePermissionMenuDTO> permissionTreeAdmin(PermissionTreeDTO permissionTreeDTO) {
        //获取场景数据
        QueryWrapper<Scene> queryWrapper = new QueryWrapper<>();
        if(permissionTreeDTO.getEnterpriseId() != null){
            Boolean flag = entManage(permissionTreeDTO.getEnterpriseId());
            if(flag){
                //运行商企业
                QueryWrapper<SceneEnterprise> queryProjectWrapper = new QueryWrapper();
                queryProjectWrapper.eq("enterprise_id",permissionTreeDTO.getEnterpriseId());
                List<SceneEnterprise> sceneEnterprises = sceneEnterpriseDao.selectList(queryProjectWrapper);
                if(!CollectionUtils.isEmpty(sceneEnterprises)){
                    List<Integer> collect = sceneEnterprises.stream().map(i -> i.getSceneId()).collect(Collectors.toList());
                    queryWrapper.in("id",collect);
                }else{
                    queryWrapper.in("id",-1);
                }
            }else {
                //入驻企业
                QueryWrapper<EnterpriseProject> enterpriseProjectQueryWrapper = new QueryWrapper<>();
                enterpriseProjectQueryWrapper.in("enterprise_id", permissionTreeDTO.getEnterpriseId());
                List<EnterpriseProject> list = enterpriseProjectDao.selectList(enterpriseProjectQueryWrapper);
                if(!CollectionUtils.isEmpty(list)) {
                    List<Integer> projectIds = list.stream().map(i -> i.getProjectId()).distinct().collect(Collectors.toList());
                    permissionTreeDTO.setProjectIds(projectIds);
                }
            }
        }
        //获取所有项目
        List<Integer> projectIds = new ArrayList<>();
        if(permissionTreeDTO.getProjectId() != null){
            projectIds.add(permissionTreeDTO.getProjectId());
        }
        if(!CollectionUtils.isEmpty(permissionTreeDTO.getProjectIds())){
            projectIds.addAll(permissionTreeDTO.getProjectIds());
        }
        //根据项目取
        if(!CollectionUtils.isEmpty(projectIds)){
            QueryWrapper<Project> queryProjectWrapper = new QueryWrapper();
            queryProjectWrapper.in("id",projectIds);
            List<Project> sceneProjects = projectService.list(queryProjectWrapper);
            if(!CollectionUtils.isEmpty(sceneProjects)){
                List<Integer> collect = sceneProjects.stream().map(i -> i.getSceneId()).collect(Collectors.toList());
                queryWrapper.in("id",collect);
            }else{
                queryWrapper.in("id",-1);
            }
        }
        if(!CollectionUtils.isEmpty(permissionTreeDTO.getSceneIds())){
            queryWrapper.in("id",permissionTreeDTO.getSceneIds());
        }
        if(null != permissionTreeDTO.getSceneId()){
            queryWrapper.eq("id",permissionTreeDTO.getSceneId());
        }
        List<Scene> scenes = sceneDao.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(scenes)){
            return null;
        }
        List<ScenePermissionMenuDTO> result = new ArrayList<>();
        ScenePermissionMenuDTO scenePermissionMenuDTO = null;
        PermissionTreeDTO param = null;
        for(Scene vo:scenes){
            scenePermissionMenuDTO = new ScenePermissionMenuDTO();
            scenePermissionMenuDTO.setScene(vo);
            param = new PermissionTreeDTO();
            param.setDevelopId(permissionTreeDTO.getDevelopId());
            param.setSceneId(vo.getId());
            param.setSceneCode(vo.getCode());
            param.setAppIdStr(permissionTreeDTO.getAppIdStr());
            param.setEnterpriseId(permissionTreeDTO.getEnterpriseId());
            param.setType(permissionTreeDTO.getType());
            //获得权限
            scenePermissionMenuDTO.setAppPermissionMenuDTOS(dealPermission(param));
            if(!CollectionUtils.isEmpty(scenePermissionMenuDTO.getAppPermissionMenuDTOS())) {
                result.add(scenePermissionMenuDTO);
            }
        }
        return result;
    }

    /**
     * 是否是运营商企业
     */
    private Boolean entManage(Integer enterpriseId){
        Enterprise enterprise = enterpriseService.findById(enterpriseId);
        if(enterprise != null && enterprise.getType().contains("1")) {
            return true;
        }else{
            return false;
        }
    }

    private List<AppPermissionMenuDTO> dealPermission(PermissionTreeDTO permissionTreeDTO){
        List<Permission> permissions = permissionQueryHandler(permissionTreeDTO);
        if (CollectionUtils.isEmpty(permissions)) {
            log.info("未查询到权限 {}", JSONObject.toJSONString(permissionTreeDTO));
            return Collections.emptyList();
        }
        //通过企业过滤
        List<Permission> result = new ArrayList<>();
        if(permissionTreeDTO.getEnterpriseId() != null){
            QueryWrapper<EnterprisePermission> enterprisePermissionQueryWrapper = new QueryWrapper<>();
            enterprisePermissionQueryWrapper.eq("enterprise_id",permissionTreeDTO.getEnterpriseId());
            enterprisePermissionQueryWrapper.select("permission_id");
            List<EnterprisePermission> enterprisePermissions = enterprisePermissionDao.selectList(enterprisePermissionQueryWrapper);
            if(CollectionUtils.isEmpty(enterprisePermissions)){
                return Collections.emptyList();
            }else{
                List<Integer> permissionIds = enterprisePermissions.stream().map(i -> i.getPermissionId()).distinct().collect(Collectors.toList());
                for(Permission vo:permissions){
                    if(permissionIds.contains(vo.getId())){
                        result.add(vo);
                    }
                }
            }
        }else{
            result = permissions;
        }
        //处理树结构
        List<PermissionDTO> permissionDTOS = generateTree(result);

        List<Permission> sort = result.stream().sorted(Comparator.comparing(Permission::getLevel).reversed()).collect(Collectors.toList());
        // 项目权限范围选择的那里不需要裁剪
        if(PermissionTypeEnum.PROJECT == permissionTreeDTO.getPermissionType()){
            if(null != permissionTreeDTO.getProjectId() || null != permissionTreeDTO.getEnterpriseId()){
                for (int i = 0; i < sort.get(0).getLevel(); i ++){
                    projectPermissionTreeCut(permissionDTOS);
                }
            }
        }
        return getPermissionTreeGroupByApp(permissionDTOS);
    }

}
